package com.sms.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.sms.common.Constants;
import com.sms.utils.TokenUtils;
import com.sms.web.rest.RestObject;
import com.sms.web.system.entity.SysUser;

/**
 * @desc token拦截器
 * @author WuJiangWu
 * @date 2018年7月22日下午4:11:03
 */
public class TokenInterceptor implements HandlerInterceptor {

	private static final Logger logger = Logger.getLogger(TokenInterceptor.class);
	
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//跨域设置
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Headers","X-Requested-With, Content-Type, Authorization,user-token");
		response.setHeader("Access-Control-Allow-Methods","GET, POST,DELETE,PUT,");
		
    	String requestPath = getRequestPath(request);//访问url
		logger.info("requestPath:"+requestPath);
		
        SysUser user = (SysUser) request.getSession().getAttribute(Constants.USER_SESSION_NAME);
        if(user != null){
            return true;
        }
        String token = request.getHeader(Constants.TOKEN_COOKIE_NAME);
        if( StringUtils.isNotBlank(token) ) {
        	user =TokenUtils.getUser(token);
            if(user != null){
                request.getSession().setAttribute(Constants.USER_SESSION_NAME,user);
                return true;
            }
        }
        
        //session过期且token过期或未登录
        RestObject restobj = RestObject.newRestObject(RestObject.STATUS_CODE_NOT_LOGIN, "未登陆或登陆已过期");
        //响应客户端
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.getWriter().print(JSONObject.toJSONString(restobj));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
    
    /**
	 * 截取访问路径
	 * 
	 * @param request
	 * @return
	 */
	public static String getRequestPath(HttpServletRequest request) {

		String requestPath = request.getRequestURI();
		// 去掉其他参数
		if (requestPath.indexOf("&") > -1) {
			requestPath = requestPath.substring(0, requestPath.indexOf("&"));
		}
		// 去掉jsessionid参数
		if(requestPath.indexOf(";") > -1){
			requestPath = requestPath.substring(0, requestPath.indexOf(";"));
		}
		// 去掉项目路径
		requestPath = requestPath.substring(request.getContextPath().length());
		return requestPath;
	}
}
